//
//  My1A2BAppDelegate.m
//  My1A2B
//
//  Created by sun ives on 2009/12/28.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "My1A2BAppDelegate.h"
#import "define_tw.h"
#import <libxml/encoding.h>
#import <libxml/xmlwriter.h>

@implementation My1A2BAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize backgroundView;
@synthesize homeViewController;
@synthesize playViewController;
@synthesize historyTableViewController;
@synthesize core;


- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    
    // Override point for customization after app launch
	navigationController = [[UINavigationController alloc] init];
	[window addSubview:navigationController.view];
	homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
	[navigationController pushViewController:homeViewController animated:YES];
	//backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
	playViewController = [[PlayViewController alloc] initWithNibName:@"PlayViewController" bundle:nil];	
	historyTableViewController = [[HistoryTableViewController alloc] initWithNibName:@"HistoryTableViewController" bundle:nil];
	
	self.core = [[Core alloc] init];
	[self loadHistory];
	
	//[window addSubview:backgroundView];
    //[window addSubview:processViewController.view];
    //[window addSubview:playViewController.view];
	//[window addSubview:homeViewController.view];
    [window makeKeyAndVisible];
}

- (void)loadHistory{
	NSString *filePath = [self getXMLPath];
	NSData *xml = [NSData dataWithContentsOfFile:filePath];
#ifdef DEBUG	
	NSString *sxml = [[NSString alloc] initWithData:xml encoding:NSUTF8StringEncoding];
	NSLog(@"%@", sxml);
	NSLog(@"%@", filePath);
#endif
	if (xml == nil) {
		[self writeXML];
	}else{
		NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xml];
		[parser setDelegate:self];
		[parser setShouldProcessNamespaces:NO];
		[parser setShouldReportNamespacePrefixes:NO];
		[parser setShouldResolveExternalEntities:NO];
		[parser parse];
		
		NSError *parseError = [parser parserError];
		if(parseError) {
			//NSError *error = parseError;
		}
		[parser release];
	}
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	if(qName) {
		elementName = qName;
	}	
	if([elementName isEqualToString:@"summary"]){
		int count = [[attributeDict valueForKey:@"count"] intValue];
		[self.core setSummaryCount:count];

	}
	if ([elementName isEqualToString:@"game"]) {
		int no = [[attributeDict valueForKey:@"no"] intValue];
		int count = [[attributeDict valueForKey:@"count"] intValue];
		NSString *answer = [attributeDict valueForKey:@"answer"];
		NSString *startTime = [attributeDict valueForKey:@"startTime"];
		NSString *guessTime = [attributeDict valueForKey:@"guessTime"];
		char *chAnswer = (char*)malloc(LIMIT);
		memset(chAnswer, '\0', LIMIT);
		char *chStartTime = (char*)malloc(LIMIT);
		memset(chStartTime, '\0', LIMIT);
		char *chGuessTime = (char*)malloc(LIMIT);
		memset(chGuessTime, '\0', LIMIT);
		[answer getCString:chAnswer maxLength:LIMIT encoding:NSUTF8StringEncoding];
		[startTime getCString:chStartTime maxLength:LIMIT encoding:NSUTF8StringEncoding];
		[guessTime getCString:chGuessTime maxLength:LIMIT encoding:NSUTF8StringEncoding];
		m_GameCurr = [self.core setGame:no count:count answer:chAnswer startTime:chStartTime guessTime:chGuessTime guess:nil];
		[self.core plusGameCount];
	}
	if ([elementName isEqualToString:@"guess"]) {
		//strGame *game = [self.history getCurrGame:m_GameNO];
		strGame *game = m_GameCurr;
		int no = [[attributeDict valueForKey:@"no"] intValue];
		NSString *number = [attributeDict valueForKey:@"number"];
		NSString *result = [attributeDict valueForKey:@"result"];
		//game->no = no;
		char *temp = (char*)malloc(LIMIT);
		memset(temp, '\0', LIMIT);
		[number getCString:temp maxLength:LIMIT encoding:NSUTF8StringEncoding];
		strcpy(game->guess[no-1].number, temp);
		memset(temp, '\0', LIMIT);
		[result getCString:temp maxLength:LIMIT encoding:NSUTF8StringEncoding];
		strcpy(game->guess[no-1].result, temp);
		free(temp);
		temp = NULL;
		//m_GuessNO++;
	}
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
	NSLog(@"Error on XML Parse: %@", [parseError localizedDescription] );
}

- (NSString *)getXMLPath{
	NSString *filename = @"/history.xml";
	//NSString *path = [[NSBundle mainBundle] resourcePath];
	//NSString *filePath = [path stringByAppendingPathComponent:filename];
	
	NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSMutableString *filePath = [NSMutableString stringWithString:[filePaths objectAtIndex:0]];
	[filePath appendString:filename];
	
	
	return filePath;
}
- (void)writeXML{
	NSString *filePath = [self getXMLPath];
	xmlTextWriterPtr _writer;
	xmlBufferPtr _buf;
	//xmlChar *_tmp;
	const char *_UTF8Encoding = "UTF-8";
	_buf = xmlBufferCreate();
	_writer = xmlNewTextWriterMemory(_buf, 0);
	char *temp;
	
	// <?xml version="1.0" encoding="UTF-8"?>
	xmlTextWriterStartDocument(_writer, "1.0", _UTF8Encoding, NULL);
	
	// <root>
	xmlTextWriterStartElement(_writer, BAD_CAST "root");
	
	// <summary count="0" />
	xmlTextWriterStartElement(_writer, BAD_CAST "summary");
	strSummary summary = [self.core getSummary];
	temp = (char*)malloc(LIMIT);
	memset(temp, '\0', LIMIT);
	sprintf(temp, "%d", summary.count);
	xmlTextWriterWriteAttribute(_writer, BAD_CAST "count", BAD_CAST temp);	
	xmlTextWriterEndElement(_writer);	
	
	strGame *game, *gameCurr;
	gameCurr = [core getGameHead];
	while (gameCurr != NULL) {
		game = gameCurr;
		// <game no="1" count="6" answer="123" startTime="2010-01-07 16:45:34" guessTime="2M:5S">
		xmlTextWriterStartElement(_writer, BAD_CAST "game");
		temp = (char*)malloc(LIMIT);
		memset(temp, '\0', LIMIT);
		sprintf(temp, "%d", game->no);		
		xmlTextWriterWriteAttribute(_writer, BAD_CAST "no", BAD_CAST temp);	
		memset(temp, '\0', LIMIT);
		sprintf(temp, "%d", game->count);		
		xmlTextWriterWriteAttribute(_writer, BAD_CAST "count", BAD_CAST temp);	
		xmlTextWriterWriteAttribute(_writer, BAD_CAST "answer", BAD_CAST game->answer);	
		xmlTextWriterWriteAttribute(_writer, BAD_CAST "startTime", BAD_CAST game->startTime);	
		xmlTextWriterWriteAttribute(_writer, BAD_CAST "guessTime", BAD_CAST game->guessTime);
		for (int i = 0; i < game->count; i++) {
			// <guess no="1" number="123" result="1A1B">
			xmlTextWriterStartElement(_writer, BAD_CAST "guess");
			memset(temp, '\0', LIMIT);
			sprintf(temp, "%d", game->guess[i].no);		
			xmlTextWriterWriteAttribute(_writer, BAD_CAST "no", BAD_CAST temp);	
			xmlTextWriterWriteAttribute(_writer, BAD_CAST "number", BAD_CAST game->guess[i].number);
			xmlTextWriterWriteAttribute(_writer, BAD_CAST "result", BAD_CAST game->guess[i].result);
			xmlTextWriterEndElement(_writer);
			// </guess>
		}
		// </game>
		xmlTextWriterEndElement(_writer);
		free(temp);
		temp = NULL;
		
		gameCurr = game->next;
	}
	// </root>
	xmlTextWriterEndElement(_writer);
	xmlTextWriterEndDocument(_writer);
	xmlFreeTextWriter(_writer);
	
	NSData *_xmlData = [NSData dataWithBytes:(_buf->content) length:(_buf->use)];
	xmlBufferFree(_buf);		
	[_xmlData writeToFile:filePath atomically:NO];
}

- (void)dealloc {
	[core destroy];
	[core release];
	[backgroundView release];
    [homeViewController release];
    [playViewController release];
    [historyTableViewController release];
    [window release];
    [super dealloc];
}


@end
